<template>
  <div class="createAlias">
    <div class="top">
      <span>新建别名<span class="back return" @click="goback">&lt;&nbsp;返回</span></span>
    </div>
    <div class="aliasMsg">
      <el-form ref="createAli" :model="alias.data" label-width="140px" label-position="left" :rules="rules" :scroll-to-error="true">
        <div class="title">
          <div class="title-label"></div>
          基本信息
        </div>
        <div class="formData">
          <el-form-item prop="name">
            <template #label>
              <div class="item-label">别名名称</div>
            </template>
            <el-input v-model="alias.data.name" maxlength="1024" />
          </el-form-item>
          <div class="description">
            <el-form-item prop="description">
              <template #label>
                <div class="item-label">描述</div>
              </template>
              <el-input :rows="2" type="textarea" v-model="alias.data.description" maxlength="1024" show-word-limit />
            </el-form-item>
          </div>
          <el-form-item prop="type" :rules="rules.type">
            <template #label>
              <div class="item-label">类型</div>
            </template>
            <el-select v-model="alias.data.type">
              <el-option v-for="i in typeOptions" :key="i.value" :label="i.label" :value="i.value" />
            </el-select>
          </el-form-item>
          <el-form-item prop="message">
            <template #label>
              <div class="item-label">消息</div>
            </template>
            <el-input v-model="alias.data.message" maxlength="1024" />
          </el-form-item>
        </div>
        <el-divider />
        <div class="title">
          <div class="title-label"></div>
          关联Fleet
          <div class="el-upload__tip">类型为激活时，至少需关联一个，其他状态可不选，支持多选</div>
        </div>
        <el-form label-position="top" :model="alias.data" ref="createAlias" :rules="rules">
          <div class="communicationitem" v-for="(ite, index) in alias.data.associated_fleets" :key="index">
            <div class="col1">
              <el-form-item :prop="'associated_fleets.' + index + '.fleet_id'" :rules="rules.fleet_id">
                <template #label v-if="index < 1">
                  <div class="item-label">Fleet&nbsp;ID</div>
                  <el-tooltip effect="dark" content="应用进程队列的id"
                    ><el-icon><QuestionFilled /></el-icon
                  ></el-tooltip>
                </template>
              </el-form-item>
              <el-select v-model="ite.fleet_id" class="m-2 fleet" placeholder="请选择fleet" @change="changeFleet">
                <el-option v-for="item in fleetOptions" :key="item.value" :label="item.label" :value="item.value" :disabled="item.disabled">
                  <div class="fleetLabel">{{ item.label }}</div>
                  <div class="fleetValue">{{ item.value }}</div>
                </el-option>
              </el-select>
            </div>
            <div class="col2">
              <el-form-item :prop="'associated_fleets.' + index + '.weight'" :rules="rules.weight">
                <template #label v-if="index < 1">
                  <div class="item-label">权重</div>
                  <el-tooltip
                    effect="dark"
                    content="当前算法为加权轮询算法，权重可填0-100之间的整数，数值越大被分发的流量越多。权重设置为0，该Fleet不会再接受新请求。"
                    ><el-icon><QuestionFilled /></el-icon
                  ></el-tooltip>
                </template>
                <el-input v-model="ite.weight" />
              </el-form-item>
            </div>
            <div class="toport" :class="[!index && 'mg-top']">
              <el-form-item>
                <div :class="alias.data.associated_fleets.length < 2 ? 'minus' : 'add'" @click="minusconfig(index)">-</div>
                <div v-if="index < 1" :class="alias.data.associated_fleets.length > 9 ? 'minus' : 'add'" @click="addconfig()">+</div>
              </el-form-item>
            </div>
          </div>
        </el-form>
        <div class="operateButton">
          <el-button class="btn button" @click="onReset">重置</el-button>
          <el-button class="btn new button" type="primary" @click="onCreate">创建</el-button>
        </div></el-form
      >
    </div>
  </div>
</template>
<style lang="scss" scoped>
  @import '@/assets/scss/dropdownBox.scss';
  .createAlias {
    .top {
      height: 60px;
      width: calc(100% - 200px);
      position: absolute;
      top: 50px;
      left: 200px;
      background-color: $blank-color;
      color: $text-color;
      display: flex;
      align-items: center;
      z-index: 100;

      span {
        font-size: 16px;
        font-weight: bold;
        margin-left: 20px;
        margin-right: 21px;
        line-height: 60px;
      }
      .return {
        margin-left: 8px;
        font-size: 14px;
      }
    }
    .aliasMsg {
      background-color: $blank-color;
      margin-top: 60px;
      padding: 30px;
      .title {
        display: flex;
        align-items: center;
        margin-bottom: 36px;
        font-weight: bold;
        font-size: 14px;
        .title-label {
          width: 4px;
          height: 14px;
          background: #325cb0;
          border-radius: 0px;
          margin-right: 6px;
        }
        :deep(.el-upload__tip) {
          margin-left: 10px;
          margin-top: 0px;
          color: #b4b6be;
          font-size: 14px;
        }
      }
      .el-form-item {
        :deep(.el-form-item__label) {
          display: inline-flex;
          align-items: center;
        }
      }
      .el-icon {
        margin: -12px 0 0 10px;
        color: #b4b6be;
      }
      .communicationitem:nth-child(1) {
        height: 90px;
      }
      .communicationitem {
        .mg-top {
          margin-top: 30px;
        }
        display: flex;
        justify-content: flex-start;
        flex-wrap: nowrap;
        margin-left: 150px;
        .col1 {
          height: 60px;
          .el-form-item {
            width: 480px;
            margin-bottom: 0px;
            margin-right: 20px;
          }
        }
        .col2 {
          height: 60px;
          .el-form-item {
            width: 280px;
            margin-bottom: 28px;
            margin-right: 100px;
          }
        }
        .toport {
          display: flex;
          .el-form-item {
            width: 320px;
            margin-bottom: 20px;
          }
        }
        .el-icon {
          position: relative;
          top: 7px;
          left: 6px;
        }
      }
      .el-form-item {
        width: 620px;
        margin-bottom: 30px;
        :deep(.el-form-item__label::before) {
          margin-left: -10px;
        }
      }
      .formData {
        margin-left: 10px;
        .description {
          .el-form-item {
            width: 940px;
          }
        }
      }
      .operateButton {
        .el-button + .el-button {
          margin-left: 0px;
        }
      }
    }
  }
</style>
<script lang="ts" setup>
  import appStore from '@/store'
  import { reactive, ref } from 'vue'
  import type { FormInstance, FormRules } from 'element-plus'
  import router from '@/router'
  import aliases, { Alias, CreateAli } from '@/api/aliases'
  import { ElMessage, ElMessageBox } from 'element-plus'
  import FleetsService from '@/api/fleetsService'
  const alias: { data: CreateAli } = reactive({
    data: {
      name: '',
      description: '',
      type: '',
      message: '',
      associated_fleets: [
        {
          fleet_id: '',
          weight: ''
        }
      ]
    }
  })
  const param = reactive({
    project_id: appStore.userStore.project_id,
    offset: 0,
    limit: 10,
    fleet_id: '',
    autoScaling: {
      name: '',
      policy_type: '',
      target_based_configuration: {
        metric_name: '',
        target_value: 0
      }
    }
  })
  interface optionList {
    value: string
    label: string
    disabled: boolean
  }
  const fleetOptions: optionList[] = reactive([])
  const getFleets = async () => {
    let res = await FleetsService.getFleets(param)
    if (res.status == 200) {
      res.data.fleets.forEach((item: any) => {
        fleetOptions.push({
          label: `${item.name}`,
          value: item.fleet_id,
          disabled: item.disabled
        })
      })
    }
  }
  getFleets()
  let submitForm: Alias = {
    project_id: appStore.userStore.project_id,
    CreateAliasRequestBody: alias.data
  }
  const rules = reactive<FormRules>({
    name: [{ required: true, message: '请输入别名名称', trigger: 'blur' }],
    description: [{ required: true, message: '请输入描述', trigger: 'blur' }],
    type: [{ required: true, message: '请选择类型', trigger: 'change' }],
    fleet_id: [{ required: false, message: '请选择fleet_id', trigger: 'change' }],
    weight: [
      { required: false, message: '请输入权重', trigger: 'blur' },
      { pattern: /^([1-9]?\d|100)$/, message: '请输入0-100之间的整数(包含0和100)' }
    ]
  })
  const createAli = ref<FormInstance>()
  const createAlias = ref<FormInstance>()
  const typeOptions = [
    {
      value: 'ACTIVE',
      label: '激活'
    },
    {
      value: 'DEACTIVE',
      label: '停用'
    }
  ]
  const minusconfig = (index: any) => {
    if (alias.data.associated_fleets.length < 2) return
    alias.data.associated_fleets.splice(index, 1)
    changeFleet(index)
  }
  const addconfig = () => {
    if (alias.data.associated_fleets.length > 9) return
    alias.data.associated_fleets.push({
      fleet_id: '',
      weight: ''
    })
  }
  const goback = () => {
    router.push({
      name: 'aliasesList'
    })
  }
  const onReset = () => {
    createAli.value!.resetFields()
    createAlias.value!.resetFields()
  }
  const changeFleet = (fleet: string) => {
    param.fleet_id = fleet
    let types: optionList[] = reactive([])
    alias.data.associated_fleets.forEach((item: any) => {
      if (item.fleet_id) {
        types.push(item.fleet_id)
      }
    })
    fleetOptions.forEach((element: any) => {
      if (types.indexOf(element.value) !== -1) {
        element.disabled = true
      } else {
        element.disabled = false
      }
    })
  }
  let creating = ref(false)
  const onCreate = async () => {
    try {
      if (creating.value) return
      let formValid = await createAlias.value?.validate((valid) => {
        return valid
      })
      let messageBox = false
      if (formValid) {
        if (alias.data.type == 'DEACTIVE') {
          alias.data.associated_fleets = alias.data.associated_fleets?.filter((item) => item.weight != '')
        }
        if (alias.data.type == 'ACTIVE') {
          alias.data.associated_fleets.forEach((item) => {
            if (item.fleet_id == '') {
              messageBox = true
            } else {
              messageBox = false
            }
          })
        }
        if (messageBox) {
          ElMessageBox.alert('类型为激活时，至少需关联一个Fleet。', '温馨提示', {
            confirmButtonText: '确定',
            type: 'warning'
          })
          return
        }
        if (alias.data.associated_fleets.length) {
          alias.data.associated_fleets.forEach((item) => {
            item.weight = item.weight * 1
          })
        }
        submitForm.CreateAliasRequestBody = alias.data
        creating.value = true
        let res = await aliases.createAlias(submitForm)
        if (res.status === 201) {
          creating.value = false
          ElMessage({
            message: '创建成功！',
            type: 'success'
          })
          router.push({
            name: 'aliasesList'
          })
        }
      }
    } catch (error) {
      creating.value = false
      ElMessage.error('创建失败')
    }
  }
</script>
